<?php
namespace Wap\Model;
use Think\Model;

class LotteryItemModel extends Model
{
	protected $tableName = "lottery_item";

    /*
    *抽奖结果返回
    */
	public function lotteryResult($lotteryId = 0,$openid = '')
	{
		$lottery = D('lottery')->where(array('id'=>$lotteryId))->find();
       
		if(!$lottery)
		{
			$result['success'] = false; //活动不存在
			$result['msg']    = '活动不存在';
			return $result; 
		}
		$count = D('Wap/lottery_record')->customerRecordNum($lotteryId, $openid);
       
		if($count >= $lottery['time_day'] )
		{
			$result['success'] = false;
			$result['msg']    = '亲，您已到达抽奖限制次数。把机会留给你的小伙伴，让TA来试试吧！';

			return $result;
		}

		//已达到当日抽奖限制次数

		$item = $this->lotteryCaculate($lottery);

		if($item == null)
		{
			$result['success'] = false;
			$result['msg'] = '很遗憾，您未中奖，请下次再来!';

            $data['lottery_id']   =  $lottery['id'];
			$data['lottery_item_id'] = 0;
			$data['status'] = 0;
			$data['createtime'] = time();
			$data['createip']   = get_client_ip();
			$data['openid']     = $openid;
            if(M('lottery_record')->add($data))
            {
            	return $result;
            }
			
		}
		else
		{
			$result['success'] = true;
			$result['item'] = $item;
			
            //插入lottery_record 中奖纪录 
			$data['lottery_id']   =  $lottery['id'];
			$data['lottery_item_id'] = $item['id'];
			$data['status'] = 1;
			$data['createtime'] = time();
			$data['createip']   = get_client_ip();
			$data['openid']     = $openid;
            if(M('lottery_record')->add($data))
            {
            	return $result;
            }

		}

		return null;

	}

    /*
    *中奖概率计算
    */
	public function lotteryCaculate($lottery)
	{
        $items = $this->where(array('lottery_id'=>$lottery['id']))->select();
        $record = D('Wap/lottery_record');
        
        foreach ($items as $key => $value) 
        {
        	$num = $record->itemRecordNum($value['id']);
        	var_dump($num);
        	if($num >= $value['num']) //奖品已发完，默认跳过
        	{
        		continue;
        	}
        	//当日奖品已发完，默认跳过（未开发）


        	$randNum = mt_rand(1, 100);
            if( $randNum < ($value['percent'] * 100) )
            {
                return $value;
            }
        }

        return null;
	}
}
?>